/*
 * Copyright (c) 2012-2013, CS Bakery. All rights reserved.
 */

package csBakery;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.Vector;

/*
 * 	@release Final Release
 *	@author  Chan Ka Yan
 *	@version 2.0.0
 * 
 * 	@release Release 2
 *	@author  Chan Ka Yan
 *	@version 1.1.5
 */

public class PriceList{
	Vector<PriceItem> vector;
	public static final String defaultLink = "price.txt";
	private String thisLink;

	public PriceList(String link){
		thisLink = link;
		openFile(link);
	}
	
	public static void clearFile(String link){
		File f = new File(link);
		if (f.exists()){
			try{
				f.delete();
				f.createNewFile();
			} catch (Exception e){
				System.out.println("Error: " + e.getMessage());
			}
		}
	}
	
	private void openFile(String link){
		try{
			//read price file from existing price file
			vector = new Vector(10);
			File f = new File(link);
			if (!f.exists()){
				f.createNewFile(); //new price file if it doesn't exists
			}
			FileInputStream fstream = new FileInputStream(f);
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str = br.readLine();
			while (str != null){
				//trim the str and add PriceItem to vector
				String temp = str;
				int index = temp.indexOf(' ');
				String name = temp.substring(0, index);
				temp = temp.substring(index+1);
				//check if the name contain two words
				while(temp.indexOf(' ') != -1){
					index = temp.indexOf(' ');
					name += " " + temp.substring(0, index);
					temp = temp.substring(index+1);
				}
				
				addNewPrice(name, Float.parseFloat(temp));
				str = br.readLine();
			}
			in.close();	 
		} catch (Exception e){
			System.out.println("PriceList Error: " + e.getMessage());
		}
	}

	public void addNewPrice(String name, float price){
		vector.add(new PriceItem(name, price));
	}
	public String toString(){
		//return all the log in one String
		String toString = "";
		for (int i = 0; i < vector.size(); i++){
			toString = new String(toString + vector.elementAt(i).toString() + "\n");
		}
		return toString;
	}
	
	public float getPrice(String name){
		for (int i = 0; i < vector.size(); i++){
			PriceItem priceItem = vector.elementAt(i);
			if (priceItem.getName().equals(name)){
				return priceItem.getPrice();
			}
		}
		return 0;
	}
	
	public class PriceItem{
		private String product;
		private float price;
		public PriceItem(String name, float price){
			this.product = name;
			this.price = price;
		}
		
		public String toString(){
			return product + " $" + price;
		}
		public String getName(){
			return product;
		}
		public float getPrice(){
			return price;
		}
	}
}
